package com.djx.分布式唯一id;

import com.djx.zk;
import com.djx.监听.ZKConnectionWatcher;
import org.apache.zookeeper.*;
import org.junit.Test;

import java.io.IOException;
import java.sql.SQLOutput;

public class GloballyUriqueId implements Watcher {
    private final String myIP = "192.168.15.132:2181";
    //用户生成序号的节点
    String defaultPath = "/uniqueId";

    ZooKeeper zooKeeper;

    public void process(WatchedEvent watchedEvent) {
        try {

            if (watchedEvent.getType() == Event.EventType.None) {
                if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
                    System.out.println("连接成功！");

                } else if (watchedEvent.getState() == Event.KeeperState.Disconnected) {
                    System.out.println("断开连接！");
                } else if (watchedEvent.getState() == Event.KeeperState.Expired) {
                    System.out.println("会话超时！");
                    zooKeeper = new ZooKeeper(myIP, 10000, new zk());

                } else if (watchedEvent.getState() == Event.KeeperState.AuthFailed) {
                    System.out.println("认证失败！");
                }
            } else if (watchedEvent.getType() == Event.EventType.NodeDataChanged) {
                System.out.println("监听到节点修改");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public GloballyUriqueId() {
        try {
            zooKeeper = new ZooKeeper(myIP, 10000, this);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getUriqueId() {
        //
        String path = "";
        try {
            //创建临时有序节点!  截取临时有序节点的id就是分布式唯一id
            String s = zooKeeper.create(defaultPath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            System.out.println("临时有序节点需要为: "+s);
            path = s;
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        uniqelID00000001;
        return path.substring(9);
    }

    @Test
    public void ID() {
        GloballyUriqueId globallyUriqueId = new GloballyUriqueId();

        for (int i = 1; i <= 5; i++) {

            String uriqueId = globallyUriqueId.getUriqueId();
            System.out.println(uriqueId);
        }

    }
}
